<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
		$this->load->model('category_model');
		$this->load->model('goods_model');
		$this->load->model('siteproduct_model');
		$this->load->model('siteorder_model');
		$this->load->model('site_model');
		$this->load->model('aliship_model');
		$this->json=["status"=>0,"msg"=>"","data"=>[]];
	}
	
	public function apisetting($siteid)
	{	
		$pushsite=$this->site_model->getitembyid($siteid);
		if(!$pushsite)
		{
			$data=["error"=>1,"msg"=>"店铺不存在"];
			echo json_encode($data,JSON_UNESCAPED_UNICODE);
			die();
		}
		$pushsite["extra"]=json_decode($pushsite["extra"],true);
		echo json_encode($pushsite,JSON_UNESCAPED_UNICODE);
		die();
	}

	public function getshopifysite()
	{
		$shopify=[];
		$sites=$this->site_model->getallsync();
		foreach($sites as $site)
		{
			if($site["sitetype"]==2)
			{
				$site["extra"]=json_decode($site["extra"],true);
				$shopify[]=$site;
			}
		}
		echo json_encode($shopify,JSON_UNESCAPED_UNICODE);
		die();
	}

	public function getproductinfo()
	{
		$result=[];
		$request = $this->uri->uri_to_assoc(3);
		$siteid = $request["siteid"];
		$rid = $request["rid"];
		$g=$this->siteproduct_model->getsitepro($siteid,$rid);
		if($g)
		{
			$result=$this->goods_model->getbyid($g["productid"]);
			if($result)
			{
				$result=unserialize($result["thumb"]);
			}
		}
		echo json_encode($result);
		die();
	}

	public function getexistids()
	{
		$request = $this->uri->uri_to_assoc(3);
		if(empty($request['key'])) die("no entry");
		$shop=$this->category_model->get_item_by_key($request['key']);
		if(empty($shop)) die("error key");

		$result=[];
		$goods=$this->goods_model->getallgoods($shop["id"],[],"tbid");
		if($goods)
		{
			foreach($goods as $g)
			{
				$result[]=$g["tbid"];
			}

		}

		echo json_encode($result);
		die();
	}
	
	public function getsiteinfo($siteid)
	{
		$site=$this->site_model->getitembyid($siteid);
		if($site)
		{
			echo json_encode(["error"=>0,"info"=>$site]);
		}
		else
		{
			echo json_encode(["error"=>1,"msg"=>"no site found"]);
		}
		die();
	}

	public function delprestashopgood()
	{
		$request = $this->uri->uri_to_assoc(3);
		$siteid = $request["siteid"];
		$productid = $request["rid"];
		$site=$this->site_model->getitembyid($siteid);
		$this->load->library('sitetype/prestashop',$site,'mysite');	

		$g=$this->siteproduct_model->getsitepro($siteid,$productid);
		if($g)
		{
			$this->mysite->delproduct(["rid"=>$productid]);
			$this->siteproduct_model->delitem($g["id"]);
			//$this->goods_model->delitem($g["productid"]);
			echo json_encode(["error"=>0,"msg"=>"del ok"]);
		}
		else
		{
			echo json_encode(["error"=>1,"msg"=>"product no exist"]);
		}
		die();
	}

	public function rebuiltproductprice()
	{
		$siteid=27;
		$site=$this->site_model->getitembyid($siteid);
		$this->load->library('sitetype/prestashop',$site,'mysite');	
		$goods=$this->siteproduct_model->getitemsfilter(["siteid"=>$siteid,"id"=>1071939]);
		foreach($goods as $g)
		{
			$og=$this->goods_model->getbyid($g["productid"]);
			if($og["source"]=="amazon")
			{
				$newprice = get_price($site["ruler"],$og["price"]);
				$result = $this->mysite->updatepro($g["rid"],["price"=>$newprice]);
				$this->siteproduct_model->update($g["id"], ["price"=>$newprice]);
				echo "update ".$g["rid"]." price : ".$result."\n";
			}

		}

		echo "all done";
		die();

	}

	public function createcate($catename)
	{
		$newdata=[
			"name"=>trim(urldecode($catename)),
			"note"=>"auto",
			"adminid"=>1
		];
		$cat = $this->category_model->create($newdata);

		echo $cat["key"];
		die();

	}


	private function refixtitle($title)
	{	

		$mark=[
			'New design','New arrival','free shipping','top Quality','high quality','good quality','Wholesale Price','Bulk price',
			'Hot-selling','Hot sell','Hot sales','Hot sale','Gift for','For gifts','For gift','High quality','By shijie','for women',
			'hot!','Hottest Sale','of the Hottest','For Girls','of the','top sale','Online Shopping','Shipping Free','100%',"[You'Re My Secret]",
			'!','[',']','(',')','.',','
		];
		
		$key=[
			'american','america','handmade','designer','design','newest','New',
			'famous','classic','beautiful','colorful','most','unique','Quality','Femininas','Feminina','Feminine','bulk',
			'Wholesale','price','Elegant','Modern','Factory','European','korean','Unique','Classic','Romantic','Fashion',
			'Charming','Style','Deluxe','Luxury','Ethnic','Generous','womens','female','dropship','hot','cheap','brand',
			'sexy','student','popular','trend','for','girls','girl','Lovely','Selling','and','Free','Cheapest'
		];
		$title=str_ireplace($mark,"",$title);
		$find=[];
		foreach($key as $k)
		{
			$find[]='/\b'.$k.'\b/i';
		}
		$title=preg_replace($find,"",$title);
		$title=preg_replace('/\s+/i'," ",$title);
		return ucwords(trim($title));
	}

	public function push(){
		
		$request = $this->uri->uri_to_assoc(3);
		if(empty($request['key'])) die("no entry");
		$shop=$this->category_model->get_item_by_key($request['key']);
		if(empty($shop)) die("error key");
		if(file_exists(APPPATH."/libraries/collect/".$request['type'].".php")){
			include APPPATH."/libraries/collect/".$request['type'].".php";
		}
		else
		{
			$sitename = $request['type'];
			include APPPATH."/libraries/collect/single.php";			
		}
		die();
	}

	public function waitorder()
	{
		$data=[];
		$orders=$this->siteorder_model->getquery();
		if($orders)
		{
			foreach($orders as $order)
			{					
				$buyo=trim($order["buy_ordersn"]);
				if(strstr($buyo,","))
				{
					$buo=explode(",",$buyo);
					foreach($buo as $bu)
					{
						if($bu)
						{
							$data[]=$bu;
						}
					}
				}
				else
				{
					$data[]=trim($order["buy_ordersn"]);
				}
			}
		}
		
		if(empty($data))
		{
			$this->json["status"]=1;
			$this->json["message"]="暂时没有订单需要检查";			
		}
		else
		{
			$this->json["status"]=0;
			$this->json["data"]=$data;
		}
		$this->sendjson();
	}

	public function buy1688price()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$order=$this->siteorder_model->getby1688oid(trim($info["id"]));
		if($order)
		{
			if(empty($info["buyamount"]))
			{
				$info["buyamount"]=str_replace(",","",$info["buyamount"]);
				$buyfee = sprintf("%.2f",($info["buyamount"]/7));
				$newdata=["buyamount"=>$buyfee];
				$this->siteorder_model->update($order["id"], $newdata);
				$this->json["message"]="ok";
				$this->sendjson();
			}
			else
			{
				$this->json["message"]="采购价不为空";
				$this->sendjson();
			}
		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}

	}

	public function buyprice()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$order=$this->siteorder_model->getbyalioid(trim($info["id"]));
		if($order)
		{
			if(empty($info["buyamount"]))
			{
				$newdata=["buyamount"=>$info["buyamount"]];
				$this->siteorder_model->update($order["id"], $newdata);
				$this->json["message"]="ok";
				$this->sendjson();
			}
			else
			{
				$this->json["message"]="采购价不为空";
				$this->sendjson();
			}
		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}

	}

	private function updateorderbyinfo($info)
	{
		$order=$this->siteorder_model->getbyalioid(trim($info["id"]));
		if($order && !$order["shiptime"])
		{
			$newdata=[];
			if(isset($info["shiptime"]))
			{
				$newdata["shiptime"]=$info["shiptime"];
			}
			if(isset($info["logistics"]))
			{
				$newdata["logistics"]=$info["logistics"];
			}
			if($newdata)
			{
				$this->siteorder_model->update($order["id"], $newdata);
			}
		}
	}

	public function testshopkey($key)
	{
		$shop=$this->category_model->get_item_by_key($key);
		if($shop)
		{			
			echo "1";
		}
		else
		{
			echo "0";
		}
		die();
	}

    public function recieve_ship()
    {
		$info=json_decode($this->input->raw_input_stream,true);
		$this->updateorderbyinfo($info);
        $shippment=$this->aliship_model->getitembykey($info["id"],"ordersn");
        if(!$shippment)
        {
            $newdata=[
				"ordersn"=>$info["id"],
				"price"=>$info["buyamount"],
                "tracklog"=>json_encode($info["track"]),
                "status"=>0,
                "shiptype"=>$info["shiptype"],
				"shipnum"=>$info["shipnum"],
				"price">$info["buyamount"],
                "paytime"=>date("Y-m-d H:i:s",strtotime($info["paytime"])),
                "updatetime"=>date("Y-m-d H:i:s"),
                "disputetime"=>date("Y-m-d H:i:s",time()+intval($info["disputetime"]/1000))
            ];
            if(isset($info["track"]["detailList"]) && count($info["track"]["detailList"])>0 && (strstr(strtolower($info["track"]["detailList"][0]["desc"]),"delivered")))
            {
                $newdata["status"]=1;
            }
            if(isset($info["keydesc"]) && strstr(strtolower($info["keydesc"]),"delivered"))
            {
                $newdata["status"]=1;
            }
            $this->aliship_model->create($newdata);
            $this->json["status"]=1;
            $this->json["message"]="ok";
        }
        else if($shippment["status"]==0)
        {
            $newdata=[
				"tracklog"=>json_encode($info["track"]),
				"price"=>$info["buyamount"],
                "shipnum"=>$info["shipnum"],
                "updatetime"=>date("Y-m-d H:i:s"),
			];
			if($info["disputetime"])
			{
				$newdata["disputetime"]=date("Y-m-d H:i:s",time()+intval($info["disputetime"]/1000));
			}
            if(isset($info["track"]["detailList"]) && count($info["track"]["detailList"])>0 && (strstr(strtolower($info["track"]["detailList"][0]["desc"]),"delivered")))
            {
                $newdata["status"]=1;
            }
            if(isset($info["keydesc"]) && strstr(strtolower($info["keydesc"]),"delivered"))
            {
                $newdata["status"]=1;
            }
            $this->aliship_model->update($shippment["id"],$newdata);
            $this->json["status"]=1;
            $this->json["message"]="ok";
        }
        else
        {
            $this->json["status"]=1;
            $this->json["message"]="done ship";
        }
        $this->sendjson();
	}
		
	public function reciver_order()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$order=$this->siteorder_model->getbyalioid(trim($info["id"]));
		if($order)
		{
			$newdata=[
				"shipping"=>$info["tracking_no"],
				"buy_shipnum"=>$info["tracking_no"],
				"buyamount"=>$info["buyamount"],
				"state"=>4
			];
			if(isset($info["trackurl"]))
			{
				$newdata["trackurl"]=$info["trackurl"];
			}
			if(isset($info["shiptime"]))
			{
				$newdata["shiptime"]=$info["shiptime"];
			}
			if(isset($info["logistics"]))
			{
				$newdata["logistics"]=$info["logistics"];
			}

			$newship=0;
			if($order["shipping"])
			{
				$newdata["shipping"]=$order["shipping"].",".$newdata["shipping"];
				$newship=1;
			}
			if($order["buy_shipnum"])
			{
				$newdata["buy_shipnum"]=$order["buy_shipnum"].",".$newdata["buy_shipnum"];
			}
			if(isset($newdata["trackurl"]) && $order["trackurl"])
			{
				$newdata["trackurl"]=$order["trackurl"].",".$newdata["trackurl"];
			}
			if($newdata["shipcount"]<=0 or strstr($order["shipping"],$info["tracking_no"]))
			{
				$this->json["message"]="error order";
				$this->sendjson();
			}

			if($order["siteid"]>0)
			{
				$site=$this->site_model->getitembyid($order["siteid"]);
				if(!empty($site))
				{
					loadsystemlink($site);
					if($this->mysite->checklink)
					{					
						$result = $this->mysite->shiporder($order["oid"],$info["tracking_no"],$newship);
						if($result=="nolocation")
						{
							$return["status"]=0;
							$return["message"]="请先设定一个发货地点，才可以发货";	
						}
					}
				}
			}
			
			$newdata["shipcount"]=$order["shipcount"]-1;
			$this->siteorder_model->update($order["id"], $newdata);
			$this->json["message"]="ok";
			$this->sendjson();

		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}
	}
	
	private function sendjson()
	{
		echo json_encode($this->json,JSON_UNESCAPED_UNICODE);
		die();
	}
	
    public function save_log($msg){
    	$logfile=APPPATH.'logs'.DIRECTORY_SEPARATOR.date("Y-m-d").".log";
    	file_put_contents($logfile,date("Y-m-d H:i:s").":".$msg.PHP_EOL,FILE_APPEND);
    }

}
